package com.example.fengyungo.activity.me;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;

import com.example.fengyungo.R;
import com.example.fengyungo.activity.BaseActivity;
import com.example.fengyungo.activity.main.OrderUserActivity;
import com.example.fengyungo.constant.DriverConstant;
import com.example.fengyungo.constant.MessageConstant;
import com.example.fengyungo.constant.OrderConstant;
import com.example.fengyungo.constant.ResultConstant;
import com.example.fengyungo.constant.TextConstant;
import com.example.fengyungo.domain.Driver;
import com.example.fengyungo.domain.Message;
import com.example.fengyungo.domain.OrderDetailsVO;
import com.example.fengyungo.utils.BitmapUtils;
import com.example.fengyungo.utils.InfoUtil;
import com.example.fengyungo.utils.OkHttpUtils;
import com.example.fengyungo.utils.OssUtils;
import com.example.fengyungo.utils.SharedPreferencesUtils;
import com.example.fengyungo.utils.ThreadPoolUtil;

import org.json.JSONObject;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * 我的中我的订单中的订单详情
 *
 * @author XLR
 */
public class MyOrderDetailActivity extends BaseActivity implements View.OnClickListener {

    private static final String TAG = "MyOrderDetailActivity";

    /**
     * 返回
     */
    ImageButton back;
    /**
     * 订单发送方用户信息
     */
    ImageButton userButton;
    /**
     * 已送达按钮
     */
    Button arriverButton;
    /**
     * 评分
     */
    RatingBar ratingBar;
    /**
     * 进度条
     */
    ProgressBar progressBar;

    private ImageView imageView;

    private TextView beginTv;

    private TextView endTv;

    private TextView priceTv;

    private TextView lengthTv;

    private TextView widthTv;

    private TextView heightTv;

    private TextView weightTv;

    private TextView noteTv;

    private TextView earliestTimeTv;

    private TextView latestTimeTv;

    private TextView orderStatusTv;

    private OrderDetailsVO orderDetailsVO;

    private Driver driver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_order_detail);

        // 从intent获取数据
        Intent intent = getIntent();
        orderDetailsVO = (OrderDetailsVO) intent.getSerializableExtra(OrderConstant.ORDER_DETAILS_VO);

        back = findViewById(R.id.back);
        ratingBar = findViewById(R.id.rating);
        userButton = findViewById(R.id.user);
        arriverButton = findViewById(R.id.button_has_arrived);
        progressBar = findViewById(R.id.progress_bar);

        // 获取司机信息
        driver = SharedPreferencesUtils.getDriverInfo(this);

        initControls();

        // 设置图片
        setImage();

        // 获取订单数据
        Integer orderStatusInt = orderDetailsVO.getOrderStatus();
        Float credit = orderDetailsVO.getCredit();

        // 根据订单状态分别显示按钮和评分
        if (orderStatusInt.equals(OrderConstant.HAS_RECEIVED)) {
            arriverButton.setVisibility(View.VISIBLE);
            ratingBar.setVisibility(View.GONE);
        } else if (orderStatusInt.equals(OrderConstant.HAS_GOT_GOODS)
                || orderStatusInt.equals(OrderConstant.HAS_ARRIVED)) {
            arriverButton.setVisibility(View.GONE);
            ratingBar.setVisibility(View.VISIBLE);
        }

        // RatingBar
        ratingBar.setRating(credit);

        // 点击事件
        back.setOnClickListener(this);
        userButton.setOnClickListener(this);
        arriverButton.setOnClickListener(this);
    }

    /**
     * 初始化控件
     */
    private void initControls() {
        imageView = findViewById(R.id.image);
        beginTv = findViewById(R.id.tv_begin);
        endTv = findViewById(R.id.tv_end);
        priceTv = findViewById(R.id.tv_price);
        lengthTv = findViewById(R.id.tv_length);
        widthTv = findViewById(R.id.tv_width);
        heightTv = findViewById(R.id.tv_height);
        weightTv = findViewById(R.id.tv_weight);
        noteTv = findViewById(R.id.tv_note);
        earliestTimeTv = findViewById(R.id.tv_earliest_time);
        latestTimeTv = findViewById(R.id.tv_latest_time);
        orderStatusTv = findViewById(R.id.tv_order_status);

        // 修改显示
        beginTv.setText(orderDetailsVO.getBegin());
        endTv.setText(orderDetailsVO.getEnd());
        priceTv.setText(String.valueOf(orderDetailsVO.getPrice()));
        lengthTv.setText(String.format("%s%s", orderDetailsVO.getLength(), OrderConstant.CM));
        widthTv.setText(String.format("%s%s", orderDetailsVO.getWidth(), OrderConstant.CM));
        heightTv.setText(String.format("%s%s", orderDetailsVO.getHeight(), OrderConstant.CM));
        weightTv.setText(String.format("%s%s", orderDetailsVO.getWeight(), OrderConstant.G));
        noteTv.setText(orderDetailsVO.getNote());
        latestTimeTv.setText(orderDetailsVO.getLatestTime());
        earliestTimeTv.setText(orderDetailsVO.getEarliestTime());
        orderStatusTv.setText(OrderConstant.STATUS_TEXT[orderDetailsVO.getOrderStatus()]);
    }

    /**
     * 设置图片
     */
    private void setImage() {
        // 从SharedPreferences中获取图片
        Bitmap bitmapFromSp = BitmapUtils.getBitmapFromSharedPreferences(this, orderDetailsVO.getNumber());
        Log.d(TAG, "setImage: bitmapFromSp=" + bitmapFromSp);
        if (bitmapFromSp == null) {
            // 从oss获取图片并存到sp中
            saveImageToSharedPreferences();
        }
        imageView.setImageBitmap(bitmapFromSp);
    }

    /**
     * 将图像存SharedPreference中
     */
    private void saveImageToSharedPreferences() {
        Runnable runnable = () -> {
            String orderImageUrl = orderDetailsVO.getImage();
            Bitmap bitmapFromOss = null;
            if (OkHttpUtils.isValidUrl(orderImageUrl)) {
                bitmapFromOss = OssUtils.getBitmapFromOss(this, orderImageUrl);
            } else {
                Log.d(TAG, "saveImageToSharedPreferences: notInvalidUrl");
            }
            Log.d(TAG, "saveImageToSharedPreferences: bitmapFromOss=" + bitmapFromOss);
            if (bitmapFromOss == null) {
                bitmapFromOss = BitmapFactory.decodeResource(getResources(), R.drawable.image);
            } else {
                BitmapUtils.saveBitmapToSharedPreferences(bitmapFromOss, this, orderDetailsVO.getNumber());
            }
            Bitmap finalBitmapFromOss = bitmapFromOss;
            runOnUiThread(() -> {
                imageView.setImageBitmap(finalBitmapFromOss);
            });
        };
        ThreadPoolUtil.execute(runnable);
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.back) {
            finish();
        } else if (id == R.id.user) {
            Intent intent = new Intent(this, OrderUserActivity.class);
            intent.putExtra(OrderConstant.USER_ID, orderDetailsVO.getUserId());
            startActivity(intent);
        } else if (id == R.id.button_has_arrived) {
            // 提示是否修改状态为已送达
            AlertDialog.Builder builder = new AlertDialog.Builder(this)
                    .setTitle(TextConstant.ALERT)
                    .setMessage(TextConstant.CHANGE_STATUS_TO_ARRIVED)
                    .setPositiveButton(TextConstant.OK, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            // 修改订单状态为已送达
                            changeStatusArrived();
                        }
                    })
                    .setNegativeButton(TextConstant.CANCEL, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            dialogInterface.dismiss();
                        }
                    });
            builder.show();
        }
    }

    /**
     * 修改订单状态为已送达
     */
    private void changeStatusArrived() {
        progressBar.setVisibility(View.VISIBLE);
        Runnable runnable = () -> {
            String url = DriverConstant.URL_USER_DRIVER + "/arrived/" + orderDetailsVO.getNumber();
            try {
                String responseData = OkHttpUtils.put(url, "");
                JSONObject jsonObject = new JSONObject(responseData);
                int code = jsonObject.getInt(ResultConstant.CODE);
                String msg = jsonObject.getString(ResultConstant.MSG);
                Log.d(TAG, "run: code:" + code);
                if (code == ResultConstant.SUCCESS) {
                    runOnUiThread(() -> {
                        progressBar.setVisibility(View.GONE);
                        Toast.makeText(MyOrderDetailActivity.this, getString(R.string.status_to_arrived), Toast.LENGTH_SHORT).show();
                        finish();
                        // todo 返回到上一个fragment时需要自动刷新
                        // 系统发消息给用户提醒
                        // 建立聊天
                        InfoUtil.addMessageList(this, orderDetailsVO.getUserId());
                        // 发送接单信息给订单发布者
                        InfoUtil.sendMessage(this, generateMessage());
                    });
                } else {
                    runOnUiThread(() -> {
                        progressBar.setVisibility(View.GONE);
                        Toast.makeText(MyOrderDetailActivity.this, msg, Toast.LENGTH_SHORT).show();
                    });
                }
            } catch (Exception e) {
                progressBar.setVisibility(View.GONE);
                Toast.makeText(MyOrderDetailActivity.this, getString(R.string.connection_error), Toast.LENGTH_SHORT).show();
            }
        };
        ThreadPoolUtil.execute(runnable);
    }

    /**
     * 生成通知
     *
     * @return Message
     */
    private Message generateMessage() {
        DateTimeFormatter formatterForId;
        DateTimeFormatter formatterForSendTime;
        String sendTime = "2000-01-01 01:00:00";
        String timeForId = "2000-01-01 01:00:00";
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            // 根据发送时间与用户id生成消息id
            formatterForId = DateTimeFormatter.ofPattern("MMddHHmmss");
            formatterForSendTime = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            LocalDateTime now = LocalDateTime.now();
            sendTime = now.format(formatterForSendTime);
            timeForId = now.format(formatterForId);
        }

        String content = "你好，你的从【" + orderDetailsVO.getBegin() + "】到【"
                + orderDetailsVO.getEnd() + "】的订单已送达。请领取后前往订单页面确认收货。";

        Message message = new Message();
        message.setReceiverId(orderDetailsVO.getUserId());
        message.setContent(content);
        message.setSenderId(MessageConstant.D_SYSTEM_ID);
        message.setSendTime(sendTime);
        message.setMessageId(driver.getId() + timeForId);
        return message;
    }
}